$(function () {
  var MAP_COLOR = ["rgba(232, 118, 222, 1)", "#F8E71C", "rgba(55,201,54,1)", "#03CEF9", "rgba(0, 255, 255, 1)", "rgba(3, 206, 249, 1)"]

  var touristSexyPieChart = echarts.init(document.getElementById('touristSexyPie'))
  var touristDaysChart = echarts.init(document.getElementById('touristDaysChart'))
  var touristNumberRatioChart = echarts.init(document.getElementById('touristNumberRatioChart'))
  var sourceAnalysisChart = echarts.init(document.getElementById('sourceAnalysisChart'))
  var scenicSpotChart = echarts.init(document.getElementById('scenicSpotChart'))

  /* === 画客源地分析图 === */
  var sourceAnalysisCityMockData = [
    [{
      name: '上海',
      value: 20000
    }, {
      name: '成都'
    }],
    [{
      name: '广州',
      value: 50000
    }, {
      name: '成都'
    }],
    [{
      name: '大连',
      value: 95000
    }, {
      name: '成都'
    }]
  ]
  var sourceAnalysisProvinceMockData = [
    [{
      name: '山西',
      value: 20000
    }, {
      name: '四川'
    }],
    [{
      name: '内蒙古',
      value: 50000
    }, {
      name: '四川'
    }],
    [{
      name: '贵州',
      value: 95000
    }, {
      name: '四川'
    }],
    [{
      name: '青海',
      value: 75000
    }, {
      name: '四川'
    }]
  ]
  var cityGeoCoorMap = null
  var provinceGeoCoorMap = null
  var sourceAnalysisType = 'city'
  toDrawSourceAnalysisChart(sourceAnalysisType)
  /* === 画游客性格分析饼图 === */
  var sexyData = {
    man: 12390,
    woman: 11980
  }
  drawPieChart(touristSexyPieChart, sexyData)
  /* === 画游客逗留天数竖状图 === */
  var touristData = [2.5, 3, 2.8, 3, 1.4, 4.2, 4.1, 5.5, 4.3, 1.2, 3.5, 1.5]
  drawTouristDaysChart(touristDaysChart, touristData)
  /* === 画景区TOP10竖状图 === */
  var scenicSpotData = [{
    name: '峨眉山',
    value: 8000
  }, {
    name: '峨眉山',
    value: 5000
  }, {
    name: '峨眉山',
    value: 5000
  }, {
    name: '峨眉山',
    value: 5000
  }, {
    name: '峨眉山',
    value: 5000
  }, {
    name: '峨眉山',
    value: 5000
  },{
    name: '峨眉山',
    value: 5000
  },{
    name: '峨眉山',
    value: 5000
  },{
    name: '峨眉山',
    value: 5000
  },{
    name: '峨眉山',
    value: 5000
  }]
  drawScenicSpotChart(scenicSpotChart, scenicSpotData)
  /* === 画省内各市出游人数对比雷达图 === */
  var touristNumberData = []
  drawTouristNumberRatioChart(touristNumberRatioChart, touristNumberData)

  $('#scenicSpotButtons').on('click', '.section-button', function () {
    clickButton($(this))
    //todo: 列表变化
  })

  $('#sourceAnalysisButtons').on('click', '.section-button', function () {
    clickButton($(this))
    sourceAnalysisType = $(this).data('type')
    toDrawSourceAnalysisChart(sourceAnalysisType)
    //todo: 列表变化
  })

  function clickButton($dom) {
    $dom.siblings().removeClass('active')
    $dom.addClass('active')
  }

  function changeVerticalGraphDataToLineData(data) {
    var result = []
    for (var len = data.length, i = 0; i < len; i++) {
      result.push(data[i] * 0.5 + 3)
    }
    return result
  }

  function drawPieChart(chartInstance, data) {
    var option = {
      tooltip: {
        trigger: 'item',
      },
      textStyle: {
        color: '#fff',
        fontSize: 16
      },
      series: [{
        name: '游客性别分析',
        type: 'pie',
        radius: '70%',
        roseType: 'radius',
        data: [{
            value: data.man,
            name: '男性',
            itemStyle: {
              normal: {
                color: '#1085C0',
                borderColor: '#03CEF9'
              }
            }
          },
          {
            value: data.woman,
            name: '女性',
            itemStyle: {
              normal: {
                color: 'rgba(55,201,54,0.60)',
                borderColor: '#37C936'
              }
            }
          }
        ],
        label: {
          normal: {
            formatter: '{b} {d}%',
          }
        },
        labelLine: {
          normal: {
            lineStyle: {
              color: '#00FFFF'
            }
          }
        },
      }]
    };

    chartInstance.setOption(option)
  }

  function drawTouristDaysChart(chartInstance, data) {
    var year = new Date().getFullYear()
    var lineStyle = {
      color: 'rgba(0,255,255,0.19)'
    }
    var option = {
      color: ['rgba(248,231,28,0.64)'],
      textStyle: {
        color: '#A3AED9',
        fontSize: 12
      },
      grid: {
        left: '12%'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        },
        backgroundColor: ' rgba(0,255,255,0.3)',
        padding: 9,
        textStyle: {
          fontSize: 14,
          color: '#fff',
        },
        extraCssText: 'box-shadow: 0 2px 4px 0 rgba(0,0,0,0.12), 0 0 6px 0 rgba(0,0,0,0.04);border-radius: 2px;',
        formatter: year + '年{b0}<br/>天数：{c0}'
      },
      xAxis: [{
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          lineStyle: lineStyle
        },
        axisTick: {
          show: false
        },
      }],
      yAxis: [{
        type: 'value',
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          margin: 25
        },
        splitLine: {
          lineStyle: lineStyle
        },
      }, {
        type: 'value',
        show: false,
      }],
      series: [{
        name: '逗留天数',
        type: 'bar',
        barWidth: '50%',
        itemStyle: {
          normal: {
            borderColor: '#F8E71C'
          }
        },
        data: data
      }, {
        name: '逗留天数',
        type: 'line',
        showSymbol: false,
        yAxisIndex: 1,
        data: changeVerticalGraphDataToLineData(data)
      }]
    }
    chartInstance.setOption(option)
  }

  function drawScenicSpotChart(chart, data) {
    var option = {
      tooltip: {
        trigger: 'item',
      },
      grid: {
        top: '5%',
        left: '10%',
        right: '6%',
        bottom: '2%',
        containLabel: true //grid 区域包含坐标轴的刻度标签。
      },
      xAxis: [{
        type: 'value',
        splitLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false
        },
      }],
      yAxis: [{
        type: 'category',
        data: _.map(data, function(item) { return item.name }),
        axisLabel: {
          textStyle: {
            color: '#A3AED9',
            fontSize: 14,
          }, //刻度标签文字颜色
        },
        axisTick: {
          show: false
        }, //取消坐标中间刻度
        axisLine: {
          show: false,
        },
        splitLine: {
          show: false
        },
      }],
      series: [{
        type: 'bar',
        barWidth: '45%',
        itemStyle: {
          normal: {
            color: 'rgba(0,255,255,0.1)',
            borderColor: 'rgba(0,255,255,0.12)'
          }
        },
        silent: true,
        data: [10000, 10000, 10000, 10000, 10000,10000,10000,10000,10000,10000]
      }, {
        type: 'bar',
        barGap: '-100%',
        data: _.map(data, function(item) { return item.value}),
        barWidth: '45%',
        z: 2,
        zlevel: 2,
        itemStyle: {
          normal: {
            color: 'rgba(55,201,54,0.60)',
            borderColor: '#37C936'
          }
        },
      }]
    };
    chart.setOption(option)
  }

  function drawTouristNumberRatioChart(chartInstance, data) {
    var option = {
      tooltip: {
        trigger: 'item',
      },
      textStyle: {
        color: '#A3AED9',
        fontSize: 14
      },
      radar: [{
        indicator: [{
            text: '宜宾市',
            max: 100
          },
          {
            text: '内江市',
            max: 100
          },
          {
            text: '绵阳市',
            max: 100
          },
          {
            text: '雅安市',
            max: 100
          },
          {
            text: '成都市',
            max: 100
          },
          {
            text: '成都市',
            max: 100
          },
          {
            text: '成都市',
            max: 100
          },
          {
            text: '成都市',
            max: 100
          },
          {
            text: '成都市',
            max: 100
          },
          {
            text: '成都市',
            max: 100
          }
        ],
        radius: 140,
        startAngle: 90,
        splitNumber: 1,
        shape: 'polygon',
        name: {
          textStyle: {
            color: '#72ACD1'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#41AD32'
          }
        },
        splitArea: {
          areaStyle: {
            color: 'rgba(53,82,175,0.37)',
            shadowColor: 'rgba(0,0,0,0.50)',
            shadowBlur: 28
          }
        },
        axisLine: {
          lineStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: '#BBE289' // 0% 处的颜色
              }, {
                offset: 0.5,
                color: 'transparent' // 100% 处的颜色
              }, {
                offset: 1,
                color: '#BBE289' // 100% 处的颜色
              }],
            }
          }
        },
      }],
      series: [{
        name: '省内各市出游人数对比',
        type: 'radar',
        symbol: 'pin',
        lineStyle: {
          normal: {
            color: '#00FFFF'
          }
        },
        areaStyle: {
          normal: {
            color: '#0DA8BB',
            opacity: 1
          },
          emphasis: {
            color: '#0DA8BB',
            opacity: 1
          }
        },
        data: [{
          value: [80, 70, 59, 88, 72, 70, 67, 55, 66, 50, 68, 76],
          label: {
            normal: {
              show: true,
              formatter: function (params) {
                return params.value
              },
              color: '#fff',
              distance: 10,
            },
            emphasis: {
              show: true
            }
          }
        }]
      }]
    }

    chartInstance.setOption(option)
  }

  function toDrawSourceAnalysisChart(type) {
    if (type === 'province') {
      if (provinceGeoCoorMap) {
        drawSourceAnalysisChart(sourceAnalysisChart, provinceGeoCoorMap, sourceAnalysisProvinceMockData)
      } else {
        $.getJSON('../js/province.json', function (result) {
          provinceGeoCoorMap = result
          drawSourceAnalysisChart(sourceAnalysisChart, provinceGeoCoorMap, sourceAnalysisProvinceMockData)
        })
      }
    } else {
      if (cityGeoCoorMap) {
        drawSourceAnalysisChart(sourceAnalysisChart, cityGeoCoorMap, sourceAnalysisCityMockData)
      } else {
        $.getJSON('../js/city.json', function (result) {
          cityGeoCoorMap = result
          drawSourceAnalysisChart(sourceAnalysisChart, cityGeoCoorMap, sourceAnalysisCityMockData)
        })
      }
    }
  }

  function drawSourceAnalysisChart(chartInstance, geoMap, data) {
    var series = getMapSeries(geoMap, data)

    var mapSerise = [{
      name: '客源地分析',
      type: 'map',
      geoIndex: 0,
      data: _.map(data, function (item) {
        return item[0]
      })
    }]

    var tooltip = {
      formatter: function (params) {
        if (params.value && typeof params.value === 'number') {
          return params.name + ':' + params.value
        }
        return params.name
      }
    }

    series = series.concat(mapSerise)
    var option = {
      tooltip: tooltip,
      visualMap: {
        show: false,
        min: 0,
        max: 100000,
        type: 'piecewise',
        calculable: true,
        color: MAP_COLOR
      },
      geo: {
        map: 'china',
        roam: false,
        left: 70,
        top: 68,
        label: {
          normal: {
            show: false,
          },
          emphasis: {
            show: false
          }
        },
        itemStyle: {
          normal: {
            areaColor: 'rgba(3,206,249,0.3)',
            borderColor: '#161C2F',
            borderWidth: 1
          },
          emphasis: {
            areaColor: ''
          }
        },
      },
      series: series
    }
    chartInstance.setOption(option, true)
  }

  var convertData = function (geoMap, data) {
    var res = [];
    for (var i = 0; i < data.length; i++) {
      var dataItem = data[i];
      var fromCoord = geoMap[dataItem[0].name];
      var toCoord = geoMap[dataItem[1].name];
      if (fromCoord && toCoord) {
        res.push({
          fromName: dataItem[0].name,
          toName: dataItem[1].name,
          coords: [fromCoord, toCoord]
        });
      }
    }
    return res
  };

  function getMapSeries(geoMap, data) {
    var planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z';
    var defaultColor = '#F8E71C';

    var destination = data[0][1]
    var source = _.map(data, function (item) {
      return item[0]
    })
    console.log(destination)
    console.log(source)

    var series = [];
    [
      [data[0][1].name, data]
    ].forEach(function (item, i) {
      series.push({
        name: item[0],
        type: 'lines',
        zlevel: 2,
        symbol: ['none', 'arrow'],
        symbolSize: 10,
        effect: {
          show: true,
          period: 6,
          trailLength: 0,
          symbol: planePath,
          symbolSize: 30
        },
        lineStyle: {
          normal: {
            color: defaultColor,
            width: 1,
            opacity: 0.6,
            curveness: 0.2
          }
        },
        data: convertData(geoMap, item[1])
      }, {
        name: item[0] + 'effectScatter',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        zlevel: 10,
        z: 10,
        itemStyle: {
          normal: {
            color: defaultColor,
          }
        },
        data: item[1].map(function (dataItem) {
          var cValue
          if (sourceAnalysisType === 'city') {
            cValue = dataItem[0].value
          }
          return {
            name: dataItem[0].name,
            value: geoMap[dataItem[0].name].concat([cValue]),
            tooltip: {
              show: !!cValue,
              formatter: function (params) {
                return params.name + ':' + params.value[2]
              }
            },
            symbolSize: 8,
          }
        }).concat({
          symbolSize: 15,
          name: item[0],
          value: geoMap[item[0]].concat([undefined])
        })
      });
    });

    return series;
  }
})
